using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using WpfMedia = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Windows.Media;
using TxTReader.Services;

namespace TxTReader.UI
{
    /// <summary>
    /// 设置更改事件参数
    /// </summary>
    public class SettingsChangedEventArgs : EventArgs
    {
        public bool HistorySettingChanged { get; set; }
        public bool HistoryWasEnabled { get; set; }
        public bool HistoryNowEnabled { get; set; }
        
        // 其他设置更改标志
        public bool FontSettingsChanged { get; set; }
        public bool ColorSettingsChanged { get; set; }
        public bool CacheSettingsChanged { get; set; }
        public bool WrapLengthChanged { get; set; }
        public bool StatusBarSettingsChanged { get; set; }
    }
    /// <summary>
    /// SettingsWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsWindow : Window
    {
        private readonly SettingsService _settingsService;
        private readonly HistoryService _historyService;
        private AppSettings _currentSettings;
        private WpfMedia.Color _selectedForegroundColor;
        private WpfMedia.Color _selectedBackgroundColor;

        // 设置更改事件
        public event EventHandler<SettingsChangedEventArgs>? SettingsChanged;

        public SettingsWindow(SettingsService settingsService, HistoryService historyService)
        {
            InitializeComponent();
            
            // 设置窗口图标（齿轮图标）
            SetWindowIcon();
            
            _settingsService = settingsService;
            _historyService = historyService;
            _currentSettings = _settingsService.Settings;
            
            LoadSettings();
            SetupEventHandlers();

            // 订阅主题变化以联动设置显示
            ThemeService.ThemeChanged += OnThemeChanged;
            // 打开时同步一次主题
            ApplyThemeToSettingsUi(ThemeService.GetCurrentTheme());
        }

        private void LoadSettings()
        {
            // 字体设置
            FontFamilyCombo.Text = _currentSettings.DefaultFontFamily;
            FontSizeTextBox.Text = _currentSettings.DefaultFontSize.ToString();

            // 颜色设置
            _selectedForegroundColor = ParseColor(_currentSettings.DefaultForegroundColor);
            _selectedBackgroundColor = ParseColor(_currentSettings.DefaultBackgroundColor);
            UpdateColorPreviews();
            
            // 缓存设置
            CacheSizeTextBox.Text = _currentSettings.CacheSize.ToString();
            PreloadBeforeTextBox.Text = _currentSettings.PreloadPagesBefore.ToString();
            PreloadAfterTextBox.Text = _currentSettings.PreloadPagesAfter.ToString();
            
            // 自动换行设置
            WrapLengthTextBox.Text = _currentSettings.WrapLength.ToString();
            
            // 显示设置 - 已移除行号设置
            
            // 状态栏设置 - 已移除自定义项目

            // 其他设置
            EnableHistoryCheck.IsChecked = _currentSettings.EnableHistory;
        }

        private void SetupEventHandlers()
        {
            // 事件处理程序设置
        }

        private void OnThemeChanged(ThemeInfo theme)
        {
            // 切换主题时，联动设置窗口显示：字体、前景、背景
            Dispatcher.Invoke(() => ApplyThemeToSettingsUi(theme));
        }

        private void ApplyThemeToSettingsUi(ThemeInfo theme)
        {
            // 只更新颜色预览，不更新字体设置（保持用户设置）
            if (theme.TextForeground is WpfMedia.SolidColorBrush fg)
            {
                _selectedForegroundColor = fg.Color;
            }
            if (theme.TextBackground is WpfMedia.SolidColorBrush bg)
            {
                _selectedBackgroundColor = bg.Color;
            }
            UpdateColorPreviews();
        }

        // 颜色预览更新
        private void UpdateColorPreviews()
        {
            ForegroundColorPreview.Background = new WpfMedia.SolidColorBrush(_selectedForegroundColor);
            BackgroundColorPreview.Background = new WpfMedia.SolidColorBrush(_selectedBackgroundColor);
        }

        // 前景色选择
        private void OnForegroundColorClick(object sender, RoutedEventArgs e)
        {
            var colorDialog = new System.Windows.Forms.ColorDialog();
            colorDialog.Color = System.Drawing.Color.FromArgb(
                _selectedForegroundColor.A,
                _selectedForegroundColor.R,
                _selectedForegroundColor.G,
                _selectedForegroundColor.B);
            
            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _selectedForegroundColor = WpfMedia.Color.FromArgb(
                    colorDialog.Color.A,
                    colorDialog.Color.R,
                    colorDialog.Color.G,
                    colorDialog.Color.B);
                UpdateColorPreviews();
            }
        }

        // 背景色选择
        private void OnBackgroundColorClick(object sender, RoutedEventArgs e)
        {
            var colorDialog = new System.Windows.Forms.ColorDialog();
            colorDialog.Color = System.Drawing.Color.FromArgb(
                _selectedBackgroundColor.A,
                _selectedBackgroundColor.R,
                _selectedBackgroundColor.G,
                _selectedBackgroundColor.B);
            
            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _selectedBackgroundColor = WpfMedia.Color.FromArgb(
                    colorDialog.Color.A,
                    colorDialog.Color.R,
                    colorDialog.Color.G,
                    colorDialog.Color.B);
                UpdateColorPreviews();
            }
        }

        // 颜色转换方法
        private WpfMedia.Color ParseColor(string colorString)
        {
            try
            {
                return (WpfMedia.Color)WpfMedia.ColorConverter.ConvertFromString(colorString);
            }
            catch
            {
                return WpfMedia.Colors.Black; // 默认黑色
            }
        }

        private string ColorToString(WpfMedia.Color color)
        {
            return $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}";
        }

        // XAML事件处理方法
        private async void OnOkClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // 复制当前设置，避免覆盖不在设置窗口中的属性（如ShowLineNumbers、SelectedEncoding等）
                var newSettings = new AppSettings
                {
                    // 从当前设置复制所有属性
                    DefaultFontFamily = _currentSettings.DefaultFontFamily,
                    DefaultFontSize = _currentSettings.DefaultFontSize,
                    DefaultForegroundColor = _currentSettings.DefaultForegroundColor,
                    DefaultBackgroundColor = _currentSettings.DefaultBackgroundColor,
                    WordWrapMode = _currentSettings.WordWrapMode,
                    WrapLength = _currentSettings.WrapLength,
                    SelectedEncoding = _currentSettings.SelectedEncoding,
                    CurrentTheme = _currentSettings.CurrentTheme,
                    CacheSize = _currentSettings.CacheSize,
                    PreloadPagesBefore = _currentSettings.PreloadPagesBefore,
                    PreloadPagesAfter = _currentSettings.PreloadPagesAfter,
                    ShowLineNumbers = _currentSettings.ShowLineNumbers, // 保留行号设置
                    EnableSearchHighlight = _currentSettings.EnableSearchHighlight,
                    ShowFileName = _currentSettings.ShowFileName,
                    ShowTotalLines = _currentSettings.ShowTotalLines,
                    ShowVisibleLines = _currentSettings.ShowVisibleLines,
                    ShowLoadedRange = _currentSettings.ShowLoadedRange,
                    EnableHistory = _currentSettings.EnableHistory,
                    DefaultEncoding = _currentSettings.DefaultEncoding,
                    MaxCacheSize = _currentSettings.MaxCacheSize,
                    ChunkSize = _currentSettings.ChunkSize,
                    WordWrap = _currentSettings.WordWrap,
                    WrapWidth = _currentSettings.WrapWidth
                };
                
                // 只更新在设置窗口中修改的属性
                newSettings.DefaultFontFamily = FontFamilyCombo.Text;
                newSettings.DefaultFontSize = double.TryParse(FontSizeTextBox.Text, out var fontSize) ? fontSize : 12;
                newSettings.DefaultForegroundColor = ColorToString(_selectedForegroundColor);
                newSettings.DefaultBackgroundColor = ColorToString(_selectedBackgroundColor);
                newSettings.WrapLength = int.TryParse(WrapLengthTextBox.Text, out var wrapLength) ? wrapLength : 80;
                newSettings.CacheSize = int.TryParse(CacheSizeTextBox.Text, out var cacheSize) ? cacheSize : 1000;
                newSettings.PreloadPagesBefore = int.TryParse(PreloadBeforeTextBox.Text, out var preloadBefore) ? preloadBefore : 2;
                newSettings.PreloadPagesAfter = int.TryParse(PreloadAfterTextBox.Text, out var preloadAfter) ? preloadAfter : 3;
                newSettings.EnableHistory = EnableHistoryCheck.IsChecked ?? true;

                System.Diagnostics.Debug.WriteLine($"SettingsWindow.OnOkClick: 保存设置 - 字体:{newSettings.DefaultFontFamily}, 大小:{newSettings.DefaultFontSize}, 缓存:{newSettings.CacheSize}");

                // 检查各种设置是否发生变化
                bool historyWasEnabled = _currentSettings.EnableHistory;
                bool historyNowEnabled = newSettings.EnableHistory;
                bool historySettingChanged = historyWasEnabled != historyNowEnabled;
                
                bool fontSettingsChanged = _currentSettings.DefaultFontFamily != newSettings.DefaultFontFamily ||
                                         _currentSettings.DefaultFontSize != newSettings.DefaultFontSize;
                
                bool colorSettingsChanged = _currentSettings.DefaultForegroundColor != newSettings.DefaultForegroundColor ||
                                          _currentSettings.DefaultBackgroundColor != newSettings.DefaultBackgroundColor;
                
                bool cacheSettingsChanged = _currentSettings.CacheSize != newSettings.CacheSize ||
                                          _currentSettings.PreloadPagesBefore != newSettings.PreloadPagesBefore ||
                                          _currentSettings.PreloadPagesAfter != newSettings.PreloadPagesAfter;
                
                bool wrapLengthChanged = _currentSettings.WrapLength != newSettings.WrapLength;
                
                bool statusBarSettingsChanged = false;
                
                // 如果历史记录从启用变为禁用，清空历史记录
                if (historyWasEnabled && !historyNowEnabled)
                {
                    System.Diagnostics.Debug.WriteLine("SettingsWindow.OnOkClick: 历史记录被禁用，清空历史数据");
                    await _historyService.ClearHistoryAsync();
                }

                await _settingsService.UpdateSettingsAsync(newSettings);
                
                // 触发设置更改事件
                SettingsChanged?.Invoke(this, new SettingsChangedEventArgs
                {
                    HistorySettingChanged = historySettingChanged,
                    HistoryWasEnabled = historyWasEnabled,
                    HistoryNowEnabled = historyNowEnabled,
                    FontSettingsChanged = fontSettingsChanged,
                    ColorSettingsChanged = colorSettingsChanged,
                    CacheSettingsChanged = cacheSettingsChanged,
                    WrapLengthChanged = wrapLengthChanged,
                    StatusBarSettingsChanged = statusBarSettingsChanged
                });
                
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OnCancelClick(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
        
        /// <summary>
        /// 设置窗口图标（齿轮图标）
        /// </summary>
        private void SetWindowIcon(System.Drawing.Icon? icon = null)
        {
            try
            {
                // 创建齿轮图标
                // 使用Path绘制齿轮：外圈齿轮 + 内圈圆
                var gearPath = "M16,4 L18,8 L22,8 L20,12 L24,14 L22,18 L18,18 L16,22 L14,18 L10,18 L8,14 L12,12 L10,8 L14,8 Z M16,10 C13.79,10 12,11.79 12,14 C12,16.21 13.79,18 16,18 C18.21,18 20,16.21 20,14 C20,11.79 18.21,10 16,10 Z";
                var geometry = Geometry.Parse(gearPath);
                var drawing = new GeometryDrawing(
                    new SolidColorBrush(System.Windows.Media.Color.FromRgb(96, 125, 139)), // 灰蓝色填充
                    new System.Windows.Media.Pen(new SolidColorBrush(System.Windows.Media.Color.FromRgb(69, 90, 100)), 1), // 深灰蓝色边框
                    geometry);
                
                var drawingGroup = new DrawingGroup();
                drawingGroup.Children.Add(drawing);
                
                var drawingImage = new DrawingImage(drawingGroup);
                drawingImage.Freeze();
                
                // 将DrawingImage转换为BitmapSource并缩放为图标大小
                var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
                var visual = new DrawingVisual();
                using (var context = visual.RenderOpen())
                {
                    context.DrawImage(drawingImage, new Rect(0, 0, 32, 32));
                }
                renderTarget.Render(visual);
                renderTarget.Freeze();
                
                Icon = renderTarget;
            }
            catch
            {
                // 如果设置图标失败，使用系统默认图标
                try
                {
                    if (icon != null)
                    {
                        Icon = Imaging.CreateBitmapSourceFromHIcon(
                            icon.Handle,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                    }
                }
                catch { }
            }
        }
    }
}
